import {
	ref
} from "vue";

const AK = "PdUXj7U3hgWUp6kjyQTrCKrK";
const SK = "RQhRdSvPpPznRU7rXdHXftIn5DO8TS0Q";


// 获取access token的函数
const getAccessToken = async () => {
	return new Promise((resolve, reject) => {
		uni.request({
			method: 'POST',
			url: `https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id=${AK}&client_secret=${SK}`,
			success(res) {
				if (res.statusCode === 200) {
					resolve(res.data.access_token);
					console.log(res);
				} else {
					reject(res);
				}
			},
			fail(err) {
				console.log(err);
				reject(err);
			},
			complete() {
				console.log("获取access_token");
			}
		});
	});
};

// 获取车牌号的函数
export const api_get_plate = async (param) => {
	try {
		uni.showLoading({
			title: "识别中",
		});
		const token = await getAccessToken();
		return new Promise((resolve, reject) => {
			uni.request({
				method: 'POST',
				url: `https://aip.baidubce.com/rest/2.0/ocr/v1/license_plate?access_token=${token}`,
				header: {
					'Content-Type': 'application/x-www-form-urlencoded',
				},
				data: param,
				success(res) {
					if (res.statusCode === 200) {
						resolve(res.data.words_result.number);
						console.log(res);
					} else {
						reject(res);
					}
					uni.hideLoading();
				},
				fail(err) {
					console.log(err);
					reject(err);
					uni.hideLoading();
				},
				complete() {
					console.log("获取车牌号");
					uni.hideLoading();
				}
			});
		});
	} catch (error) {
		console.error("Failed to get access token:", error);
		throw error;
		uni.hideLoading();
	}
};